# agents/factor_agents/terrae_agent.py
from .base_factor_agent import BaseFactorAgent
from game_engine.game_state import FactorDevelopment, GameWorld
import numpy as np

class TerraeAgent(BaseFactorAgent):
    """丹恒腾荒智能体 - 护盾召唤特化 [火种：大地]"""
    
    def __init__(self, factor: FactorDevelopment, game_world: GameWorld):
        super().__init__(factor, game_world)
        self.personality_traits.update({
            "aggression": 0.2,      # 低攻击性
            "caution": 0.95,        # 极高谨慎性
            "defense_focus": 0.9,   # 防御专注
            "earth_connection": 0.85  # 大地连接
        })
        self.active_shields = {}
        self.defensive_structures = []
        self.last_fortify_time = 0
    
    def make_decision(self, current_time: int) -> str:
        """丹恒腾荒的决策逻辑"""
        situation = self.evaluate_situation()
        
        # 紧急防御
        if situation["critical_allies"]:
            most_critical = min(situation["critical_allies"], 
                              key=lambda x: x.attributes['health'])
            return f"emergency_shield:{most_critical.name}"
        
        # 维持重要护盾
        weak_shields = [shield for shield, info in self.active_shields.items() 
                       if info["strength"] < 30]
        if weak_shields:
            most_important = max(weak_shields, 
                               key=lambda x: self.active_shields[x]["priority"])
            return f"reinforce_shield:{most_important}"
        
        # 部署防御结构
        if (len(self.defensive_structures) < 2 and 
            current_time - self.last_fortify_time > 40):
            self.last_fortify_time = current_time
            return "deploy_defensive_structure"
        
        # 预判性护盾
        if situation["anticipated_damage"]:
            most_threatened = max(situation["anticipated_damage"], 
                                key=lambda x: x["threat_level"])
            return f"preemptive_shield:{most_threatened['ally'].name}"
        
        # 强化自身防御
        return "fortify_position"
    
    def evaluate_situation(self) -> Dict:
        """评估当前局势"""
        nearby_factors = self.get_nearby_factors(25.0)
        
        critical_allies = []
        anticipated_damage = []
        
        for factor in nearby_factors:
            if not self._is_potential_threat(factor):
                # 濒死盟友
                if factor.attributes['health'] < factor.attributes['health'] * 0.3:
                    critical_allies.append(factor)
                
                # 预判伤害威胁
                threat_level = self._calculate_threat_level(factor)
                if threat_level > 5:
                    anticipated_damage.append({
                        "ally": factor,
                        "threat_level": threat_level
                    })
        
        return {
            "critical_allies": critical_allies,
            "anticipated_damage": anticipated_damage,
            "active_shields": len(self.active_shields),
            "defensive_structures": len(self.defensive_structures),
            "defensive_readiness": self._calculate_defensive_readiness()
        }
    
    def _calculate_threat_level(self, ally: FactorDevelopment) -> float:
        """计算对盟友的威胁等级"""
        threat_level = 0
        
        # 检查附近敌人
        nearby_enemies = self.get_nearby_factors(15.0)
        enemy_count = len([f for f in nearby_enemies if self._is_potential_threat(f)])
        threat_level += enemy_count * 3
        
        # 盟友的防御状态
        if ally.attributes['defense'] < 20:
            threat_level += 5
        if ally.attributes['health'] < 50:
            threat_level += 3
        
        return threat_level
    
    def _calculate_defensive_readiness(self) -> float:
        """计算防御准备度"""
        shield_coverage = min(1.0, len(self.active_shields) / 5.0)
        structure_bonus = len(self.defensive_structures) * 0.2
        return min(1.0, shield_coverage + structure_bonus)